package com.opensource.component.extend.point.support;

import com.opensource.component.extend.point.anntation.EnableSpecificExtend;
import com.opensource.component.extend.point.metadata.SpecificExtendMetadata;
import com.opensource.component.extend.point.metadata.SpecificExtendMetadataHelper;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author zhanglong and since on 2022/12/13 8:39 下午
 */

@Configuration
@Import({ExtendPointRegistrar.class})
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@EnableSpecificExtend(basePackages = "com.opensource.component.extend.point")
@ConditionalOnProperty(name = "tax.project.specific.extend.enabled", havingValue = "true", matchIfMissing = true)
public class SpecificExtendAutoConfiguration implements BeanDefinitionRegistryPostProcessor {

    /**
     * 针对原始bean存在@Primary注解，扩展后进行覆盖
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        final String[] beanDefinitionNames = registry.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            final BeanDefinition beanDefinition = registry.getBeanDefinition(beanDefinitionName);
            if (!beanDefinition.isPrimary()) {
                continue;
            }
            for (SpecificExtendMetadata specificExtendMetadata : SpecificExtendMetadataHelper.extendPointMetadata()) {
                if (null == beanDefinition.getBeanClassName()) {
                    if (specificExtendMetadata.getSuperBeanClass().getSimpleName().equalsIgnoreCase(beanDefinitionName)) {
                        beanDefinition.setPrimary(false);
                    }
                } else {
                    if (beanDefinition.getBeanClassName().equals(specificExtendMetadata.getSuperBeanClass().getName())) {
                        beanDefinition.setPrimary(false);
                    }
                }
            }

        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }

}
